﻿Imports System.IO
Imports System.ComponentModel
Imports SACommon

<ToolboxItem(False)>
Public Class ucDownloadFiles
    Private mDownloaded As SAEventArgs
    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        '// The DefaultConnectionLimit is 2, which means you can normally only do two
        '// simultaneous downloads. This code allows you to change the limit.
        Net.ServicePointManager.DefaultConnectionLimit = 2
        btnRetry.Visible = False
        btnRetry.Enabled = False

        If Directory.Exists(gUpdateFiles.DownloadDirectory) = False Then Directory.CreateDirectory(gUpdateFiles.DownloadDirectory)
        If Directory.Exists(gUpdateFiles.ExtractDirectory) = False Then Directory.CreateDirectory(gUpdateFiles.ExtractDirectory)

        'Do a check to see if all the files have been downloaded.
        mDownloaded = gUpdateFiles.CheckDownloaded()
    End Sub
    Private Sub Me_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
        lblMessage.Text = ""
        'Do a check to see if all the files have been downloaded.
        If mDownloaded.Result <> SAEventArgs.Results.Success Then
            DoRequiredDownloads()
        Else
            NextStep()
        End If
    End Sub
    Sub DoRequiredDownloads()
        Dim tDownloadFile As String
        Dim tDestinationFile As String
        RemoveAllItems()
        lblMessage.Text = "Downloading files ..."
        Application.DoEvents()

        For Each dlfile In gUpdateFiles.DownloadFileList
            tDownloadFile = (String.Format("{0}/{1}.ZIP", gUpdateVersion.RepositoryFileUpdateFolder, dlfile.UniqueFilename)).Trim
            tDestinationFile = String.Format("{0}{1}.ZIP", gUpdateFiles.DownloadDirectory, dlfile.UniqueFilename)
            ListViewEx.StartDownload(tDownloadFile, tDestinationFile)
        Next
    End Sub
    Sub RemoveAllItems()
        Dim wClient As DownloadFileAsyncExtended

        '// Always loop backwards when removing items from the list,
        '// because the index gets updated when an item is removed.
        '// This can result in certain items not getting removed.
        For i As Integer = ListViewEx.Items.Count - 1 To 0 Step -1
            If ListViewEx.Items(i).Tag IsNot Nothing Then
                '// Get the DownloadFileAsyncExtended class instance from the ListViewItem Tag.
                wClient = DirectCast(ListViewEx.Items(i).Tag, DownloadFileAsyncExtended)
                '// Pause (cancel) the download and remove it from the list.
                wClient.CancelAsync()
                ListViewEx.Items(i).Tag = Nothing
                ListViewEx.Items(i).Remove()
            Else
                '// There's nothing to cancel, because the
                '// download has finished or caused an error.
                '// Just remove the item from the list.
                ListViewEx.Items(i).Remove()
            End If
        Next
    End Sub
    Private Sub me_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) Handles MyBase.Disposed
        Dim wClient As DownloadFileAsyncExtended

        For i As Integer = 0 To ListViewEx.Items.Count - 1
            '// Check if the Tag isn't Nothing, because else the download has already
            '// finished or an error occurred, so it can't be cancelled.
            If ListViewEx.Items(i).Tag IsNot Nothing Then
                '// Get the DownloadFileAsyncExtended class instance from the ListViewItem Tag.
                wClient = DirectCast(ListViewEx.Items(i).Tag, DownloadFileAsyncExtended)
                '// Cancel the download if it's still busy.
                wClient.CancelAsync()
            End If
        Next
    End Sub
    Private Sub btnRetry_Click(sender As Object, e As EventArgs) Handles btnRetry.Click
        If gUpdateFiles.CheckDownloaded.Result <> SAEventArgs.Results.Success Then
            DoRequiredDownloads()
        Else
            btnRetry.Visible = False
            lblMessage.Text = "Downloads completed ..."
            btnAction.Enabled = True
        End If
    End Sub
    Private Sub btnAction_Click(sender As Object, e As EventArgs) Handles btnAction.Click
        NextStep()
    End Sub
    Sub NextStep()
        gApp.ChangePage(MyApp.ApplicationType.Install, True)
    End Sub
#Region "Download files"
    Private Sub ListViewEx_DownloadsDone(Downloads As Integer, Success As Boolean) Handles ListViewEx.DownloadsDone
        Application.DoEvents()
        Dim a = From x In gUpdateFiles.DownloadFileList
        If a.Count = Downloads And Success = True Then
            lblMessage.Text = "Downloads completed ..."
            btnAction.Enabled = True
        Else
            lblMessage.Text = "The download process failed, please retry ..."
            btnRetry.Visible = True
            btnRetry.Enabled = True
        End If
    End Sub
    Private Sub ListViewEx_DownloadsProgress(Downloaded As Integer, TotalDownloads As Integer) Handles ListViewEx.DownloadsProgress
        lblMessage.Text = String.Format("Downloaded {0} of {1} ({2}%)", Downloaded, TotalDownloads, CInt(Downloaded / TotalDownloads) * 100)
        Application.DoEvents()
    End Sub
    Private Sub ListViewEx_MouseUp(ByVal sender As Object, ByVal e As MouseEventArgs) Handles ListViewEx.MouseUp
        Dim objListViewItem As ListViewItem

        Dim objDrawingPoint As Point = ListViewEx.PointToClient(Cursor.Position)

        '// Check to see if an item has been selected.
        If Not IsNothing(objDrawingPoint) Then
            With objDrawingPoint
                objListViewItem = ListViewEx.GetItemAt(.X, .Y)
            End With
        End If
    End Sub
#End Region
End Class
